package graphics.screens;

import function.Mp3File;
import function.search.EventListener;
import graphics.SearchChoiceInput2;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;

import boot.Boot;

public class Mp3ListScreen extends Canvas implements CommandListener {

	private final Command cancelCommand = new Command("Cancel", Command.EXIT, 1);

	SearchChoiceInput2 mp3ListDisplay;
	private Mp3File[] mp3s;

	public Mp3ListScreen(Mp3File[] someMp3s) {
		mp3s = someMp3s;
		mp3ListDisplay = new SearchChoiceInput2(getTitlesFrom(mp3s));
		mp3ListDisplay.addListener(new EventListener() {

			public void processEvent(String event) {
				if (EventListener.EVENT_PROCESS_DONE.equals(event)) {
					int chosen = mp3ListDisplay.getchosenIndex();
					Boot.getInstance().enqueueMp3(mp3s[chosen]);
				} else if (EventListener.EVENT_REPAINT_REQUIRED.equals(event)) {
					repaint();
				}
			}
		});
		mp3ListDisplay.gotoLastPage();
	}

	protected void paint(Graphics graphics) {
		addCommand(cancelCommand);
		setCommandListener(this);
		mp3ListDisplay.repaint(graphics);
	}

	public void keyPressed(int keyCode) {
		mp3ListDisplay.keyPressed(keyCode);
		repaint();
	}

	public void commandAction(Command command, Displayable dis) {
		if (command == cancelCommand) {
			Boot.getInstance().cancelNewList();
		}
	}

	private String[] getTitlesFrom(Mp3File[] mp3Files) {
		String[] titles = new String[mp3Files.length];

		for (int i = 0; i < mp3Files.length; i++) {
			titles[i] = mp3Files[i].getTitle();
		}

		return titles;
	}
}
